import java.net.*;
import java.io.*;

public class TexasReceiver {
	private ServerSocket accepter;
	private String recentMessage;
	private NotificationCenter notifier;
	private boolean host;
	private String tableName;
	public TexasReceiver(int port) throws IOException {
		accepter = new ServerSocket(port);
		System.out.println("Server IP address: " + accepter.getInetAddress());
		host = false;
	}
	public void setNotificationListener(NotificationCenter n){
		notifier = n;
	}
	public void setDeviceAsHost(boolean b,String tableName){
		host = b;
		this.tableName = tableName;
	}
	public void listen() throws IOException {
		for (;;) {
			Socket s = accepter.accept();
			SocketEchoThread echoer = new SocketEchoThread(s,this,notifier);
			if (host){
				echoer.makeHost(true, tableName);
			}
			System.out.println("Connection accepted from " + s.getInetAddress());
			echoer.start();
		}
	}

	public static void main(String[] args) throws IOException {
		TexasReceiver s = new TexasReceiver(Integer.parseInt(args[0]));
		s.listen();
	}
	public void closeListener(){
		try {
			accepter.close();
		} catch (IOException e) {
			System.out.print("Connection Failed to Close");
		}
	}
	public boolean recentMessageReady(){
		return recentMessage != null;
	}
	public void setMostRecent(String s){
		recentMessage = s;
	}
	public String getMostRecent(){
		return recentMessage;
	}
}